<template>
  <div>
    <modify-storage
      ref="specieFiction"
      @getBank="getStorage"
      :onRobot="onRobot"
    />
    <q-table
      class="no-border-radius full-height bg-transparent"
      card-container-class="q-pl-sm q-pr-sm q-pb-sm content-start overflow-auto"
      grid
      :rows="storageList"
      :filter="filter"
      :pagination="{ rowsPerPage: 16 }"
      hide-header
    >
      <template v-slot:top-right>
        <div class="row q-gutter-x-md items-center">
          <q-btn
            no-caps
            :class="ui.btnClass"
            icon="add"
            :label="
              onRobot
                ? $t('StorageManage.添加自身库')
                : $t('StorageManage.添加库位')
            "
            @click="specieFiction.show(null, optionsIndex)"
            v-if="optionsIndex.length !== 0 || !onRobot"
          />
          <q-toggle
            :label="$t('StorageManage.自身库')"
            v-model="onRobot"
            :class="ui.isDark ? 'text-white' : ''"
          />
          <template v-if="$q.screen.gt.xs">
            <q-input
              outlined
              dense
              v-model="filter"
              :placeholder="$t('StorageManage.搜索')"
              :dark="ui.isDark"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>
          </template>
        </div>
      </template>
      <template v-slot:item="props">
        <div class="q-pa-sm col-xs-6 col-sm-4 col-md-3">
          <q-card :class="ui.cardClass">
            <q-card-section
              class="text-h6"
              @click="specieFiction.show(props.row, optionsIndex)"
            >
              {{ props.row.name }}
              <q-btn
                flat
                icon="delete"
                class="float-right"
                color="red-5"
                @click.stop="remove(props.row)"
              />
            </q-card-section>
            <q-separator :dark="ui.isDark" />
            <q-list
              dense
              class="q-pa-sm"
              @click="specieFiction.show(props.row, optionsIndex)"
              :dark="ui.isDark"
            >
              <q-item dense clickable v-ripple v-if="onRobot">
                <q-item-section>{{ $t("StorageManage.序号") }}</q-item-section>
                <q-item-section side>{{ props.row.index }}</q-item-section>
              </q-item>
              <q-item dense clickable v-ripple v-else>
                <q-item-section>{{ $t("StorageManage.分组") }}</q-item-section>
                <q-item-section side>{{ props.row.group }}</q-item-section>
              </q-item>
              <q-item dense clickable v-ripple>
                <q-item-section>{{
                  $t("StorageManage.库规格")
                }}</q-item-section>
                <q-item-section side
                  >{{ props.row.length }}x{{ props.row.width }}x{{
                    props.row.height
                  }}
                </q-item-section>
              </q-item>
            </q-list>
            <q-btn
              no-caps
              :label="$t('StorageManage.编辑库内连线')"
              icon-right="share"
              class="full-width"
              :class="ui.btnClass"
              @click="postureTieLine(props.row)"
            />
          </q-card>
        </div>
      </template>
    </q-table>
  </div>
</template>
<script setup>
import { onMounted, ref, watch, computed } from "vue";
import { api } from "boot/axios";
import { useAPIStore } from "stores/api";
import { useUiStore } from "stores/ui";
import ModifyStorage from "components/posture/ModifyStorage.vue";
import { useQuasar } from "quasar";
import { useFunctionsStore } from "stores/functions";
import { useRouter } from "vue-router";
import { status } from "src/utils/deviceWs";
import { useI18n } from "vue-i18n";

const t = useI18n().t;
const $q = useQuasar();
const router = useRouter();
const ui = useUiStore();
const storageList = ref([]); // 获取所有规格
const originStorageList = ref([]); // 获取所有规格
const filter = ref(""); // 过滤搜索
const specieFiction = ref(); // 添加规格里数据
const onRobot = ref(false); // 是否显示自身库
const optionsIndex = ref([]); // 自生库列表
const device = computed(() => status.value.device);

onMounted(() => {
  // 生成库位
  optionsIndex.value = numberArray(useFunctionsStore().storageNumber);
  // 调用获取库位，并且赋值默认值
  getStorage(onRobot.value);
});

// 监听切换状态
watch(onRobot, (value) => {
  sense(value);
});
watch(device, (value) => {
  sense(false);
});

// 切换库位条件判断 state:页面打开默认库，修改后或者添加后立马重新计算序号
function sense(state) {
  if (state) {
    $q.notify({ message: t("StorageManage.切换到自身库"), type: "positive" });
    storageList.value = originStorageList.value.filter(
      (item) =>
        item.onRobot === onRobot.value && item.robotId === status.value.device
    );
    // 重新赋值计算
    optionsIndex.value = numberArray(useFunctionsStore().storageNumber);
    // 过滤出自生库上的序号并生成数组
    const result = originStorageList.value
      .filter(
        (item) =>
          item.onRobot === onRobot.value && item.robotId === status.value.device
      )
      .map((item) => item.index);
    // 通过库位列表判断里面不包含的数组显示
    optionsIndex.value = optionsIndex.value.filter(
      (item1) => !result.includes(item1)
    );
  } else {
    $q.notify({ message: t("StorageManage.切换到普通库"), type: "positive" });
    storageList.value = originStorageList.value.filter(
      (item) =>
        item.onRobot === onRobot.value && item.robotId === status.value.device
    );
  }
}

// 根据配置生成库位数组
function numberArray(number) {
  const arr = [];
  for (let i = 1; i <= number; i++) {
    arr.push(i);
  }
  return arr;
}

// 获取库位 state:修改后或者添加后可显示对应的页面
function getStorage(state) {
  api
    .get(useAPIStore().postureUrl + "new/storage/scenario", {
      params: { scenario: useFunctionsStore().scene.id },
    })
    .then((rs) => {
      if (rs.data.code === 200) {
        storageList.value = rs.data.data;
        originStorageList.value = storageList.value;
        // 赋值状态触发筛选
        onRobot.value = state;
        // 条件重新筛查
        sense(state);
      } else {
        $q.notify({
          message: t("StorageManage.获取库位失败"),
          type: "negative",
        });
      }
    });
}

// 删除库位
function remove(data) {
  $q.dialog({
    dark: ui.isDark,
    title: t("StorageManage.删除库位"),
    message: t("StorageManage.是否要删除该库位"),
    cancel: t("cancel"),
    ok: t("ok"),
  }).onOk(() => {
    api
      .delete(useAPIStore().postureUrl + "new/storage/" + data.id)
      .then((rs) => {
        if (rs.data.code === 200) {
          $q.notify({
            message: t("StorageManage.删除库位成功"),
            type: "positive",
          });
          getStorage(true);
        } else {
          $q.notify({
            message: t("StorageManage.删除库位失败"),
            type: "negative",
          });
        }
      })
      .catch(() => {
        $q.notify({
          message: t("RequestError"),
          type: "negative",
        });
      });
  });
}

// 库位连线
function postureTieLine(data) {
  router.push({
    path: "/PostureConnect",
    query: {
      id: data.id,
      title:
        t("StorageManage.库位") +
        "-" +
        data.name +
        "-" +
        t("StorageManage.编辑连线"),
    },
  });
}
</script>
<style scoped></style>
